package com.topfinance.cnaps2.web.listener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author MZ
 * 
 */
public class ApplicationListener implements ServletContextListener,
		HttpSessionListener {

	private static Log log = LogFactory.getLog(ApplicationListener.class);
    private ServletContext context = null;
	public static String REAL_PATH = "";
    private final static String LOCALES_KEY="locales";
	@SuppressWarnings("unchecked")
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		log.info("*******Service startup *********");
        context = servletContextEvent.getServletContext();
		String path = servletContextEvent.getServletContext().getRealPath("/");
		//log.debug("pathhhhhhhhhhh:" + path);
		REAL_PATH = path;
        context.setAttribute(LOCALES_KEY, initLocaleData());
	}

	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		log.info("*******contextDestroyed*********");
	}

	public void sessionCreated(HttpSessionEvent event) {
		try {
			log.info("session id:" + event.getSession().getId());
		} catch (Exception e) {
			log.info(e.getMessage());
		}
	}

	public void sessionDestroyed(HttpSessionEvent event) {
		try {
			log.info("sessionDestroyed, session id:"
					+ event.getSession().getId());
//			String sessionTmpDir = this.REAL_PATH + File.separator
//					+ Constants.SESSION_TEMP_DATA_DIR + File.separator
//					+ event.getSession().getId();
//			 FileUtil.removeDir(sessionTmpDir);
		} catch (Exception e) {
			log.info(e.getMessage());
		}
	}
    private Map initLocaleData(){
        Properties props   =   new   Properties();   
        InputStream   input=  null;
        try{
        	input=   this.getClass().getClassLoader().getResourceAsStream("/config/general.properties");   
            props.load(input);   
        }catch(Exception   e){
        	log.error("",e);
        }finally{
        	try {
				input.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

        Map<String, String> locales =new TreeMap<String, String>();
        locales.put(Locale.ENGLISH.toString(),props.getProperty("language.select.en"));
        locales.put(Locale.CHINA.toString(),props.getProperty("language.select.zh.cn"));
        locales.put(Locale.TAIWAN.toString(),props.getProperty("language.select.zh.tw"));
        return locales;
    }
}
